package com.test.platform.controller;

import com.test.platform.model.DeveloperInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.test.platform.service.developer.DeveloperInfoService;  // 修改包路径
import com.test.platform.service.common.GitCodeApiClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;  // 添加这行导入

@RestController
@RequestMapping("/api/developer-info")
public class DeveloperInfoController {
    private static final Logger logger = LoggerFactory.getLogger(DeveloperInfoController.class);

    @Autowired
    private GitCodeApiClient gitCodeApiService;
    
    @Autowired
    private DeveloperInfoService developerInfoService;
    
    @PostMapping("/update-all-repos")
    public ResponseEntity<String> updateAllRepos() {
        try {
            gitCodeApiService.updateAllRepos();
            return ResponseEntity.ok("所有仓库PR信息更新成功");
        } catch (Exception e) {
            logger.error("批量更新仓库失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("更新失败: " + e.getMessage());
        }
    }

    @PostMapping("/toggle-update")
    public ResponseEntity<Boolean> toggleUpdate() {
        boolean status = developerInfoService.toggleUpdateEnabled();
        return ResponseEntity.ok(status);
    }

    @GetMapping("/update-status")
    public ResponseEntity<Boolean> getUpdateStatus() {
        return ResponseEntity.ok(developerInfoService.isUpdateEnabled());
    }
    
    @GetMapping
    public ResponseEntity<List<DeveloperInfo>> getAllDeveloperInfos() {
        return ResponseEntity.ok(developerInfoService.getAllDeveloperInfos());
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<DeveloperInfo> getDeveloperInfoById(@PathVariable Integer id) {
        DeveloperInfo developerInfo = developerInfoService.getDeveloperInfoById(id);
        if (developerInfo != null) {
            return ResponseEntity.ok(developerInfo);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @GetMapping("/search/owner")
    public ResponseEntity<List<DeveloperInfo>> getDeveloperInfosByOwner(
            @RequestParam String owner) {
        List<DeveloperInfo> developerInfos = developerInfoService.getDeveloperInfosByOwner(owner);
        return ResponseEntity.ok(developerInfos);
    }

    @GetMapping("/search/name")
    public ResponseEntity<List<DeveloperInfo>> getDeveloperInfosByName(
            @RequestParam String name) {
        List<DeveloperInfo> developerInfos = developerInfoService.getDeveloperInfosByName(name);
        return ResponseEntity.ok(developerInfos);
    }

    // 修改现有的搜索接口
    @GetMapping("/search")
    public ResponseEntity<List<DeveloperInfo>> getDeveloperInfosByOwnerAndName(
            @RequestParam(required = false) String owner, 
            @RequestParam(required = false) String name) {
        List<DeveloperInfo> developerInfos;
        if (owner != null && name != null) {
            developerInfos = developerInfoService.getDeveloperInfosByOwnerAndName(owner, name);
        } else if (owner != null) {
            developerInfos = developerInfoService.getDeveloperInfosByOwner(owner);
        } else if (name != null) {
            developerInfos = developerInfoService.getDeveloperInfosByName(name);
        } else {
            developerInfos = developerInfoService.getAllDeveloperInfos();
        }
        return ResponseEntity.ok(developerInfos);
    }
    
    @PostMapping
    public ResponseEntity<DeveloperInfo> createDeveloperInfo(@RequestBody DeveloperInfo developerInfo) {
        boolean success = developerInfoService.createDeveloperInfo(developerInfo);
        if (success) {
            return ResponseEntity.ok(developerInfo);
        } else {
            return ResponseEntity.badRequest().build();
        }
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<DeveloperInfo> updateDeveloperInfo(
            @PathVariable Integer id, 
            @RequestBody DeveloperInfo developerInfo) {
        developerInfo.setId(id);  // 保持原有ID
        boolean success = developerInfoService.updateDeveloperInfo(developerInfo);
        if (success) {
            return ResponseEntity.ok(developerInfo);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteDeveloperInfo(@PathVariable Integer id) {
        try {
            logger.info("接收到删除开发者信息请求: id={}", id);
            boolean result = developerInfoService.deleteById(id);
            if (result) {
                return ResponseEntity.ok().body(Map.of(
                    "success", true,
                    "message", "删除成功"
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "删除失败"
                ));
            }
        } catch (Exception e) {
            logger.error("删除开发者信息时发生错误", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "删除失败: " + e.getMessage()
            ));
        }
    }

    @DeleteMapping("/batch")
    public ResponseEntity<?> batchDeleteDeveloperInfos(@RequestBody List<Integer> ids) {
        try {
            logger.info("接收到批量删除开发者信息请求: ids={}", ids);
            boolean result = developerInfoService.deleteByIds(ids);
            if (result) {
                return ResponseEntity.ok().body(Map.of(
                    "success", true,
                    "message", "批量删除成功"
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "批量删除失败"
                ));
            }
        } catch (Exception e) {
            logger.error("批量删除开发者信息时发生错误", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "批量删除失败: " + e.getMessage()
            ));
        }
    }
    
    @PostMapping("/update-latest-pr")
    public ResponseEntity<String> updateLatestPR(@RequestParam String owner, @RequestParam String name) {
        try {
            gitCodeApiService.updateLatestPR(owner, name);
            return ResponseEntity.ok("PR信息更新成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("更新PR信息失败: " + e.getMessage());
        }
    }
}